package com.qf.electronic.mall.login.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.qf.constant.RedisConstant;
import com.qf.dto.ResultBean;
import com.qf.entity.TUser;
import com.qf.login.api.ILoginService;
import com.qf.mapper.TUserMapper;
import com.qf.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public ResultBean checkIsLogin(String uuid) {
        if(uuid!=null&&!"".equals(uuid)){
            //组织键
            String redisKey = StringUtil.getRedisKey(RedisConstant.USER_LOGIN, uuid);
            //redis中查询
            Object o = redisTemplate.opsForValue().get(redisKey);
            if(o!=null){
                TUser user=(TUser)o;
                user.setPassword("");
                return ResultBean.ok("用户已登录",user);
            }

        }
        return ResultBean.fail("用户为登录");
    }

    @Override
    public ResultBean checkLogin(String uname, String password) {
        Example example = new Example(TUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uname",uname);
        List<TUser> user = tUserMapper.selectByExample(criteria);
        if(user.get(0)!=null){
                if(password!=null&&!"".equals(password)&&encoder.matches(password,user.get(0).getPassword())){
                    return ResultBean.ok("登录成功",user.get(0));
                }
        }
        return ResultBean.fail("用户名或密码错误");
    }
}
